package com.jspgou.cms.action.store;

import static com.jspgou.cms.Constants.STORE_SYS;
import static com.jspgou.common.page.SimplePage.cpn;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.jspgou.cms.entity.OrderItem;
import com.jspgou.cms.entity.OrderItemVo;
import com.jspgou.cms.entity.Payment;
import com.jspgou.cms.entity.Product;
import com.jspgou.cms.entity.Shipping;
import com.jspgou.cms.entity.ShopMember;
import com.jspgou.cms.entity.Store;
import com.jspgou.cms.manager.OrderItemMng;
import com.jspgou.cms.manager.PaymentMng;
import com.jspgou.cms.manager.ProductMng;
import com.jspgou.cms.manager.ShippingMng;
import com.jspgou.cms.web.CmsUtils;
import com.jspgou.cms.web.ShopFrontHelper;
import com.jspgou.cms.web.SiteUtils;
import com.jspgou.common.page.Pagination;
import com.jspgou.common.util.ExportExcel;
import com.jspgou.common.web.CookieUtils;
import com.jspgou.common.web.RequestUtils;
import com.jspgou.common.web.springmvc.MessageResolver;
import com.jspgou.core.entity.Website;

@Controller
public class ProductSellFroAct {
	private static final Logger log = LoggerFactory.getLogger(ProductSellFroAct.class);
	
	/**
	 * 商品销售列表页
	 */
	public static final String PRODUCT_SELLLIST = "tpl_sellList";
	/**
	 * 商品销售查看页
	 */
	public static final String PRODUCT_SELLVIEW = "tpl_sellView";
	
	@RequestMapping(value = "/sell/list*.jspx")
	public String list(String cl,Long ctgId,Boolean isOnSale,
			Long typeId,Double startSalePrice,Double endSalePrice,
			Integer startStock,Integer endStock,Integer pageNo, 
			HttpServletRequest request, ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		//用户没有登录，跳转到登录页
		if(member == null){
			return "redirect:../login.jspx";
		}
		Store store=member.getStore();
		if(store==null){
			return "redirect:registerStore.jspx";
		}
		String productName = RequestUtils.getQueryParam(request, "productName");
		productName = StringUtils.trim(productName);
		String brandName = RequestUtils.getQueryParam(request, "brandName");
		brandName = StringUtils.trim(brandName);
		Pagination pagination = manager.getPage(web.getId(),ctgId,store.getId(),
				productName,brandName,null,isOnSale,null,null, typeId,
				startSalePrice,endSalePrice,startStock,endStock,cpn(pageNo), CookieUtils.getPageSize(request));
		model.addAttribute("productName", productName);
		model.addAttribute("brandName",brandName);
		model.addAttribute("isOnSale", isOnSale);
		model.addAttribute("typeId",typeId);
		model.addAttribute("startSalePrice", startSalePrice);
		model.addAttribute("endSalePrice", endSalePrice);
		model.addAttribute("startStock",startStock);
		model.addAttribute("endStock", endStock);
		model.addAttribute("pagination",pagination);
		model.addAttribute("ctgId", ctgId);
		model.addAttribute("cl", cl);
		ShopFrontHelper.setCommonData(request, model, web);
		ShopFrontHelper.frontPageData(request, model);
		return web.getTplSys(STORE_SYS, MessageResolver.getMessage(request,
				PRODUCT_SELLLIST), request);
	}
	
	@RequestMapping(value = "/sell/view*.jspx")
	public String view(Long id,Long paymentId,Long shippingId,String code,
			String userName,String startTime,String endTime,Integer status,
			HttpServletRequest request, ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		//用户没有登录，跳转到登录页
		if(member == null){
			return "redirect:../login.jspx";
		}
		Store store=member.getStore();
		if(store==null){
			return "redirect:registerStore.jspx";
		}
		SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
		if(StringUtils.isBlank(startTime)){
			model.addAttribute("startTime", null);
		}else{
		  model.addAttribute("startTime", startTime);
		}
		if(StringUtils.isBlank(endTime)){
			model.addAttribute("endTime", null);
		}else{
		  model.addAttribute("endTime", endTime);
		}
	    Date start=null;
	    Date end=null;
	    try {
	       if(!StringUtils.isBlank(startTime)){
			  start=df.parse(startTime);
	      }else{
	    	  start=null;
	       } 
        if(!StringUtils.isBlank(endTime)){
	    	end=df.parse(endTime);
	    }else{
	    	end=null;
	    }
		} catch (ParseException e) {
			e.printStackTrace();
		}
		List<Shipping> shippingList = shippingMng.getList(web.getId(),null,null, true);
		List<Payment> paymentList = paymentMng.getList(web.getId(), true);
		model.addAttribute("paymentList", paymentList);
		model.addAttribute("shippingList", shippingList);
		if(id==null){
			return "redirect:list*.jspx";
		}
		Product bean=manager.findById(id);
		model.addAttribute("bean", bean);
		List<OrderItem> list = orderItemMng.getList(web.getId(),bean.getId(),paymentId,shippingId,store.getId(),
				code,start,end,status);
		Double tatal=0.0;
		Long totalCount=(long)0;
		for(OrderItem item : list){
			tatal+=item.getSalePrice()*item.getCount();
			totalCount+=item.getCount();
		}
		model.addAttribute("tatal", tatal);
		model.addAttribute("totalCount", totalCount);
		model.addAttribute("paymentId", paymentId);
		model.addAttribute("shippingId", shippingId);
		model.addAttribute("userName", userName);
		model.addAttribute("startTime", startTime);
		model.addAttribute("endTime", endTime);
		model.addAttribute("status", status);
		model.addAttribute("code", code);
		model.addAttribute("storeId", store.getId());
		ShopFrontHelper.setCommonData(request, model, web);
		ShopFrontHelper.frontPageData(request, model);
		return web.getTplSys(STORE_SYS, MessageResolver.getMessage(request,
				PRODUCT_SELLVIEW), request);
	}
	
	@RequestMapping(value ="/sell/v_excel.jspx")
	public void excel(Long id,Long paymentId,Long shippingId,String code,
			String userName,String startTime,String endTime,Integer status,
			HttpServletRequest request, HttpServletResponse response) throws IOException {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		Store store=member.getStore();
		Product bean=manager.findById(id);
		SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
	    Date start=null;
	    Date end=null;
	    try {
	       if(!StringUtils.isBlank(startTime)){
			  start=df.parse(startTime);
	      }else{
	    	  start=null;
	       } 
        if(!StringUtils.isBlank(endTime)){
	    	end=df.parse(endTime);
	    }else{
	    	end=null;
	    }
		} catch (ParseException e) {
			e.printStackTrace();
		}
		List<OrderItem> list = orderItemMng.getList(web.getId(),bean.getId(),paymentId,shippingId,store.getId(),
				code,start,end,status);
		Double total=0.0;
		Long totalCount=(long)0;
		for(OrderItem item : list){
			total+=item.getSalePrice()*item.getCount();
			totalCount+=item.getCount();
		}
		List<OrderItemVo> listVo=new ArrayList<OrderItemVo>();
		for(OrderItem item : list){
			OrderItemVo orderItemVo=new OrderItemVo();
			orderItemVo.setCode(String.valueOf(item.getItemOrder().getCode()));
			orderItemVo.setPrice(item.getSalePrice());
			orderItemVo.setDate(item.getItemOrder().getCreateTime());
			orderItemVo.setCount(item.getCount());
			orderItemVo.setPayment(item.getItemOrder().getPayment().getName());
			orderItemVo.setShipping(item.getItemOrder().getShipping().getName());
			if(item.getItemOrder()!=null){
				if(item.getItemOrder().getReturnOrder()!=null){
					if(item.getItemOrder().getPaymentStatus()==2&&item.getItemOrder().getShippingStatus()==2&&item.getItemOrder().getReturnOrder().getStatus()==5){
						orderItemVo.setStatus("(已发货)待退款订单");
					}else if(item.getItemOrder().getPaymentStatus()==2&&item.getItemOrder().getShippingStatus()==1&&item.getItemOrder().getReturnOrder().getStatus()==2){
						orderItemVo.setStatus("(未发货)待退款订单");
					}else if(item.getItemOrder().getPaymentStatus()==2&&item.getItemOrder().getShippingStatus()==1&&item.getItemOrder().getReturnOrder().getStatus()==6){
						orderItemVo.setStatus("(未发货)以退款订单");
					}else if(item.getItemOrder().getPaymentStatus()==2&&item.getItemOrder().getShippingStatus()==2&&item.getItemOrder().getReturnOrder().getStatus()==6){
						orderItemVo.setStatus("(以发货)以退款订单");
					}
				}else{
					if(item.getItemOrder().getPaymentStatus()==1){
						orderItemVo.setStatus("待付款");
					}else if(item.getItemOrder().getShippingStatus()==2&&item.getItemOrder().getStatus()==1){
						orderItemVo.setStatus("待收货");
					}else if(item.getItemOrder().getPaymentStatus()==2&&item.getItemOrder().getShippingStatus()==1){
						orderItemVo.setStatus("等待发货");
					}else if(item.getItemOrder().getStatus()==4&&item.getItemOrder().getPaymentStatus()==2&&item.getItemOrder().getShippingStatus()==2){
						orderItemVo.setStatus("已完成的订单");
					}
				}
			}
			listVo.add(orderItemVo);
		} 
		OrderItemVo orderItemVo=new OrderItemVo();
		orderItemVo.setShipping("销售数量："+totalCount);
		orderItemVo.setStatus("销售总金额:"+total);
		listVo.add(orderItemVo);
	    //构造输出对象，可以从response输出，直接向用户提供下载   
	    response.setContentType("application/vnd.ms-excel;charset=gbk");
	    response.addHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(bean.getName()+"销售统计.xls", "UTF-8"));
        OutputStream out = response.getOutputStream(); 
        ExportExcel ex = new ExportExcel();   
        String[] heads={"订单编号","商品金额","购买数量","购买时间","支付方式","配送方式","状态",};
        ex.exportExcel(heads, listVo, out) ;
	}
	
	@Autowired
	private ProductMng manager;
	@Autowired
	private PaymentMng paymentMng;
	@Autowired
	private ShippingMng shippingMng;
	@Autowired
	private OrderItemMng orderItemMng;
}
